package vn.mobisoft.gachno;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;


import android.os.AsyncTask;

//The class that takes the callback
class Network extends AsyncTask <String, String, String>
{
	private String result;
	NetworkInterface callback;
	
	public void onConnectListener(NetworkInterface n) {
		callback = n;
	}
	
	@Override
    protected void onPreExecute() {  
		callback.startNetworkConnect();
		//System.out.println("onPreExecute");
        //showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }
	
	@Override
	protected String doInBackground(String... arg0) {
		//System.out.println("doInBackground");
		try {
			result = getHttpStream(arg0[0]);
			//System.out.println("result:"+result);
		} catch (IOException e) {
			callback.networkError(e);
			e.printStackTrace();
		}
		return null;
	}
	
    @Override
    protected void onCancelled() {

    }
    
    @Override
    protected void onProgressUpdate(String... progress) {
    	callback.networkProgressUpdate(progress);
    	//System.out.println("onProgressUpdate");
    	//mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }
    
    @Override
    protected void onPostExecute(String unused) { 
    	//System.out.println("onPostExecute");
    	callback.stopNetworkConnect(result);
    }    
    
    private String getHttpStream(String urlString) throws IOException {
    	//System.out.println(urlString);
        InputStream in = null;    
        int response = -1;

        URL url = new URL(urlString); 
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");

        try{
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect(); 

            response = httpConn.getResponseCode();                 

            if (response == HttpURLConnection.HTTP_OK) {
               in = httpConn.getInputStream();                                 
            }
        } catch (Exception e) {
            throw new IOException("Error connecting:  "+e.toString());            
        } // end try-catch
        
        if (in!=null){
	        BufferedReader r = new BufferedReader(new InputStreamReader(in));
	        StringBuilder total = new StringBuilder();       
	        String line;	        
	        while ((line = r.readLine()) != null) {
	            total.append(line);
	        }	
	        return total.toString(); 
        }else return "";
    }
}
